package lambda;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class TestLambda {

	public static void main(String args[]) {

		
	}

	/**
	 * 线程
	 **/
	public static void testThread() {
		new Thread(() -> System.out.println("In Java8, Lambda expression rocks !!")).start();
	}

	/**
	 * forEach
	 **/
	public static void testForEach() {
		List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
		features.forEach(n -> System.out.println(n));
	}

	/**
	 * 模拟list类里 filter 方法
	 */
	public static void testFilter() {
		filter(Arrays.asList(new String[] { "fan", "xxx" }), s -> s.contains("f"));
	}

	/***
	 * predicate 用法 and()、or()和xor()，用于将传入 filter()
	 */
	public static void testPredicate() {

		Predicate<String> startsWithJ = (n) -> n.startsWith("J");
		Predicate<String> fourLetterLong = (n) -> n.length() == 4;
		List<String> names = Arrays.asList(new String[] { "fan", "xxx" });
		names.stream()// ==
				.filter(startsWithJ.and(fourLetterLong))// 联接两个predicate
				.forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n));
	}

	/**
	 * map reduce 操作
	 ***/
	public static void testMapReduce() {

		// 不使用lambda表达式为每个订单加上12%的税
		List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
		for (Integer cost : costBeforeTax) {
			double price = cost + .12 * cost;
			System.out.println(price);
		}

		// 使用lambda表达式
		List<Integer> costBeforeTax2 = Arrays.asList(100, 200, 300, 400, 500);
		costBeforeTax2.stream().map((cost) -> cost + .12 * cost).forEach(System.out::println);
	}

	// stream 里的filter 等方法
	public static void filter(List<String> names, Predicate<String> condition) {
		for (String name : names) {
			if (condition.test(name)) {
				System.out.println(name + " ");
			}
		}
	}
}
